package at.sysarch.filter;

import java.awt.image.WritableRaster;

import javax.media.jai.PlanarImage;

import at.sysarch.utils.ImageChangedEvent;
import at.sysarch.utils.ImageChangedListener;

public class CountTheNutsFilter extends AbstractListenerManager implements ImageChangedListener {

	PlanarImage _image = null;
	private static final int BLACK = 0;
	int _nutCount = 0;
	WritableRaster _imageRaster;

	public void setInputImage(PlanarImage image) {
		_image = image;
		updateImage();
	}

	@Override
	public void imageChanged(ImageChangedEvent event) {
		setInputImage(event.getImage());
	}

	private void updateImage() {
		countNuts();
		fireImageChanged(_image);
	}

	public void saveCount() {
		System.out.println("CountTheNuts found " + _nutCount + " nuts!");
		_nutCount = 0;
	}

	public void countNuts() {

		_imageRaster = _image.copyData();
		double[] pixel = new double[3];
		
		for (int i = 0; i < _imageRaster.getWidth(); i++) {
			for (int j = 0; j < _imageRaster.getHeight(); j++) {

				_imageRaster.getPixel(i, j, pixel);

				if (pixel[0] == BLACK && pixel[1] == BLACK && pixel[2] == BLACK) {
					_nutCount++;
					greyOutNut(i, j, pixel);
				}
			}
		}
		saveCount();
	}

	private void greyOutNut(int i, int j, double[] rgb) {
		double[] grey = { 250, 250, 250 };
		double[] pixel = new double[3];

		if (rgb[0] == BLACK && rgb[1] == BLACK && rgb[2] == BLACK) {
			_imageRaster.setPixel(i, j, grey);
			
			if (j < _image.getHeight()-1 && i < _image.getWidth()-1  && i > 0 && j > 0) {
				greyOutNut(i - 1, j - 1, _imageRaster.getPixel(i - 1, j - 1, pixel));
				greyOutNut(i, j - 1, _imageRaster.getPixel(i, j - 1, pixel));
				greyOutNut(i + 1, j - 1, _imageRaster.getPixel(i + 1, j - 1, pixel));
				greyOutNut(i - 1, j, _imageRaster.getPixel(i - 1, j, pixel));
				greyOutNut(i + 1, j, _imageRaster.getPixel(i + 1, j, pixel));
				greyOutNut(i - 1, j + 1, _imageRaster.getPixel(i + 1, j, pixel));
				greyOutNut(i, j + 1, _imageRaster.getPixel(i, j + 1, pixel));
				greyOutNut(i + 1, j + 1, _imageRaster.getPixel(i + 1, j + 1, pixel));
			}
			
		}
	}
}
